package com.my.vote;

import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.DialogFragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.my.vote.adapter.MainAdapter;
import com.my.vote.entity.EUser;
import com.my.vote.entity.EVoteInfo;
import com.my.vote.entity.req.ReqVoteList;
import com.my.vote.pst.main.IPstMain;
import com.my.vote.ui.AboutActivity;
import com.my.vote.ui.LoginActivity;
import com.my.vote.ui.MySigUpVoteListActivity;
import com.my.vote.ui.MyVoteListActivity;
import com.my.vote.ui.PublishNormalActivity;
import com.my.vote.ui.UserActivity;
import com.my.vote.ui.VoteInfoActivity;
import com.my.vote.widget.SwipeRefreshMoreLayout;
import com.sfh.lib.AppCacheManager;
import com.sfh.lib.mvp.IPresenter;
import com.sfh.lib.mvp.annotation.RxBusEvent;
import com.sfh.lib.mvp.service.LoaderService;
import com.sfh.lib.ui.AbstractActivity;
import com.sfh.lib.ui.DialogView;
import com.squareup.picasso.MemoryPolicy;
import com.squareup.picasso.Picasso;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.loader.ImageLoaderInterface;

import java.util.Arrays;
import java.util.List;

/**
 * 功能描述:主页
 *
 * @author  Xiao Jingxiang 肖景翔
 * @date 2018/4/11
 */
public class MainActivity extends AbstractActivity
        implements NavigationView.OnNavigationItemSelectedListener, IPstMain.IVMain, SwipeRefreshMoreLayout.OnLoadingListener {

    SwipeRefreshMoreLayout refreshMoreLayout;

    ImageView ivHead;
    TextView tvName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        this.init();
    }

    private void init() {
        // 设置标题栏
        Toolbar toolbar = this.findViewById(R.id.toolbar);
        this.setSupportActionBar(toolbar);

        // 发布按钮
        this.findViewById(R.id.fab).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 查询缓存用户对象数据
                EUser user = AppCacheManager.newInstance().getCache(VoteApplication.USER, new EUser());
                if (!user.isLogin()) {
                    //进入登录
                    LoginActivity.startUI(MainActivity.this, 1);
                    return;
                }
                // 进入发布
                PublishNormalActivity.startUI(MainActivity.this);

            }
        });

        //左上角按钮-设置点击效果
        DrawerLayout drawer = this.findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        //左侧滑动视图
        NavigationView navigationView = this.findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        // 设置头像-名称
        ivHead = navigationView.getHeaderView(0).findViewById(R.id.ivHead);
        tvName = navigationView.getHeaderView(0).findViewById(R.id.tvName);
        ivHead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EUser user = AppCacheManager.newInstance().getCache(VoteApplication.USER, new EUser());
                if (!user.isLogin()) {
                    //进入登录
                    LoginActivity.startUI(MainActivity.this, 1);
                    return;
                }
                UserActivity.startUI(MainActivity.this);
            }
        });
        EUser user = AppCacheManager.newInstance().getCache(VoteApplication.USER, new EUser());
        if (user.isLogin()) {
            Picasso.with(this).load(user.getHeadUrl()).into(ivHead);
            tvName.setText(user.getUserName());
        }

        // 设置首页头部幻灯片
        View view = View.inflate(this, R.layout.activity_main_top, null);
        this.setBanner(view);
        MainAdapter adapter = new MainAdapter(this);
        adapter.addHeaderView(view);

        // 设置刷新控件
        refreshMoreLayout = findViewById(R.id.base_refresh);
        refreshMoreLayout.setOnLoadingListener(this);
        refreshMoreLayout.setAdapter(adapter, true);
        refreshMoreLayout.addItemDecorationSize(5);
        refreshMoreLayout.onAutoRefresh();
        refreshMoreLayout.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                // 点击投票Item-进入详情界面
                EVoteInfo info = (EVoteInfo) adapter.getItem(position);
                VoteInfoActivity.startUI(MainActivity.this, info.getObjectId());
            }
        });

    }

    private void setBanner(View view) {
        Banner banner = view.findViewById(R.id.banner);
        //设置图片加载器
        banner.setImageLoader(new ImageLoaderInterface<ImageView>() {
            @Override
            public void displayImage(Context context, Object path, ImageView imageView) {
                //Picasso 加载图片简单用法
                Picasso.with(getApplication()).load(Integer.valueOf(String.valueOf(path))).memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE).into(imageView);
            }

            @Override
            public ImageView createImageView(Context context) {
                return new ImageView(context);
            }
        });
        //设置banner样式
        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);

        //设置图片集合
        Integer[] images = {R.mipmap.xhd1, R.mipmap.xhdp2, R.mipmap.xhdp3};
        banner.setImages(Arrays.asList(images));

        //banner设置方法全部调用完毕时最后调用
        banner.start();
    }


    @Override
    public void onBackPressed() {
        // 返回键监听-收回左侧划出视图
        DrawerLayout drawer = this.findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }


    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.nav_camera) {

            // 查询缓存用户对象数据
            EUser user = AppCacheManager.newInstance().getCache(VoteApplication.USER, new EUser());
            if (!user.isLogin()) {
                //进入登录
                LoginActivity.startUI(MainActivity.this, 1);
                return true;
            }
            // 进入我发布投票
            MyVoteListActivity.startUI(MainActivity.this);
        } else if (id == R.id.nav_gallery) {

            // 查询缓存用户对象数据
            EUser user = AppCacheManager.newInstance().getCache(VoteApplication.USER, new EUser());
            if (!user.isLogin()) {
                //进入登录
                LoginActivity.startUI(MainActivity.this, 1);
                return true;
            }
            // 进入我参加投票
            MySigUpVoteListActivity.startUI(MainActivity.this);
        } else if (id == R.id.nav_slideshow) {
            // 进入关于
            AboutActivity.startUI(MainActivity.this);
        } else if (id == R.id.nav_signout) {
            // 退出当前账号
            DialogView dialogView = new DialogView.Builder().setLeftText("NO").setRightText("YES")
                    .setMessage("Do you decide to quit the current account?").setRightListener(new DialogView.DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogFragment dialogFragment, int i) {
                            AppCacheManager.newInstance().removeCache(true, VoteApplication.USER);
                            ivHead.setImageResource(R.mipmap.ic_launcher_round);
                            tvName.setText("");
                            dialogFragment.dismiss();
                        }
                    }).build();
            showDialog(dialogView);
        }

        //收回左侧划出视图
        DrawerLayout drawer = this.findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    IPstMain pstMain;

    @Override
    public IPresenter getPresenter() {
        // 获取业务请求对象
        if (pstMain == null) {
            pstMain = LoaderService.getService(IPstMain.class);
        }
        return pstMain;
    }

    int nowPage = 0;

    @Override
    public void onRefreshUI() {
        // 下拉刷新请求
        this.nowPage = 0;
        ReqVoteList req = new ReqVoteList();
        req.setNowPage(nowPage);
        pstMain.listPage(req);
    }

    @Override
    public void onLoadMoreUI() {
        // 加载更多请求
        this.nowPage += 1;
        ReqVoteList req = new ReqVoteList();
        req.setNowPage(nowPage);
        pstMain.listPage(req);
    }

    @Override
    public void onPageList(int nowPage, int allSize, List<EVoteInfo> page) {
        // 返回投票列表数据
        this.nowPage = nowPage;
        this.refreshMoreLayout.onRefreshCompale(page, this.nowPage != 0);
        if (nowPage == allSize) {
            this.refreshMoreLayout.onLoadAllCompale();
        }
    }

    @Override
    public void onPageError(String error) {
        // 投票列表数据请求失败
        this.refreshMoreLayout.onLoadMoreFail();
        this.showToast(error);
    }

    @RxBusEvent(taskId = 1000, eventClass = EUser.class)
    public void onLogin(EUser user) {
        // 用户登录成功刷新左侧视图
        if (user.isLogin()) {
            Picasso.with(this).load(user.getHeadUrl()).into(ivHead);
            tvName.setText(user.getUserName());
        }
    }

}
